package com.itheima.rocketmq.rocketmqdemo.base.consumer;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;

import java.util.List;

/**
 * 消息的接受者
 *
 * @description:
 * @author: ycc
 * @time: 2021/3/24
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
//        1.创建消费者consumer，制定消费者组名
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group2");
//        2.指定Nameserver地址
        consumer.setNamesrvAddr("127.0.0.1:9876;127.0.0.1:9877");
//        3.订阅主题Topic和Tag
        consumer.subscribe("base2", "Tag2");
        //clustering负载均衡的模式消费 BROADCASTING广播
        consumer.setMessageModel(MessageModel.CLUSTERING);
//        4.设置回调函数，处理消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
                for (MessageExt msg : msgs) {
                    System.out.println(new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });
//        5.启动消费者consumer
        consumer.start();
    }
}


